<?php
/**
 * Created by PhpStorm.
 * User: User
 * Date: 2017/11/21
 * Time: 16:02
 */

namespace App\Controller;

use View;
use DB;

class UserController extends BaseController
{

    public function Index()
    {
        echo '用户首页！';
    }

    public function loginPage()
    {
        View::show('admin/login');
    }

    public function login()
    {
        //print_r($_POST);
        $uid = $_POST['uid'];
        $pwd = $_POST['pwd'];

        DB::table('user')->where('password', '=', $pwd);

        if (filter_var($uid, FILTER_VALIDATE_EMAIL)) {
            DB::where('email', '=', $uid);
        } else {
            DB::where('user_name', '=', $uid);
        }

        $user = DB::first();

        if ($user) {
            session_start();
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['user_name'] = $user['user_name'];
            //如果选择自动登录
            if (isset($_POST['auto_login'])) {
                $token = MD5($user['user_name'] . uniqid() . time());
                //写入数据库
                DB::table('user')
                    ->where('id', '=', $user['id'])
                    //->debug()
                    ->update(['remember_token' => $token]);

                //写入cookie
                setcookie('rem_token', $token, time() + 3600 * 24 * 7);
            }

            //header("Location: /admin");
            $this->redirect('/admin');

        } else {
            View::set('msg', '帐号密码错误！');
            View::show('admin/login');
        }
    }

}